package com.pin.zheng.xingmulibrary.util;

public class HexUtil {
    public static String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        char[] hexArray = "0123456789ABCDEF".toCharArray();
        for (int j = 0; j < bytes.length; j++) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }

    public static byte[] hexToByteArray(String hexString) {
        int hexlen = hexString.length();
        byte[] result;
        if (hexlen % 2 == 1) {
            //奇数
            hexlen++;
            result = new byte[(hexlen / 2)];
            hexString = "0" + hexString;
        } else {
            //偶数
            result = new byte[(hexlen / 2)];
        }
        int j = 0;
        for (int i = 0; i < hexlen; i += 2) {
            result[j] = (byte) Integer.parseInt(hexString.substring(i, i + 2), 16);
            j++;
        }
        return result;
    }



    /**
     * Convert char to byte
     *
     * @param c char
     * @return byte
     */
    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }


    /**
     * 将16进制字符串转换为byte[]
     *
     * @param hexString String
     * @return          byte[]
     */
    public static byte[] hexString2ByteArray(String hexString) {
        try {
            if (hexString == null || hexString.equals("")) {
                return null;
            }
            hexString = hexString.toUpperCase();
            int length = hexString.length() / 2;
            char[] hexChars = hexString.toCharArray();
            byte[] d = new byte[length];
            for (int i = 0; i < length; i++) {
                int pos = i * 2;
                d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
            }
            return d;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 校验和必然是256的整数倍,如果有余数则认为校验和失败
     *
     * @return false 校验失败 反正成功
     */
    public static boolean checkValue(String hexLineStr) {
        byte[] buf = hexString2ByteArray(hexLineStr.substring(1));
        if(buf==null){
            return false;
        }
        byte temp = 0;
        for (byte aBuf : buf) {
            temp += aBuf;
        }
        return temp % 0xFF == 0;
    }


}
